<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\api\controller;

use app\api\ApiController;
use app\common\model\User;
use app\common\support\WechatValidate;
use think\facade\Session;
use Xin\Thinkphp5\Hint\Facade\Hint;

class LoginController extends ApiController{

	/**
	 * 登录
	 *
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
	 * @throws \app\common\exception\WechatException
	 */
	public function login(){
		$type = $this->request->param('type', 'wechat');
		$code = $this->request->param('code', '', 'trim');

		if(empty($code)){
			return Hint::error("code invalid.");
		}

		if($type === 'alipay'){
			$origin = 2;
			list($sessionKey, $openid) = $this->getAlipayLoginResult($code);
		}else{
			$origin = 1;
			list($sessionKey, $openid) = $this->getWechatLoginResult($code);
		}

		$extResult = [];

		/** @var \app\common\model\User $user */
		$user = $this->user->loginUsingCredential('openid', $openid, function() use ($openid, $origin){
			return $this->makeUser($openid, $origin);
		});

		$user->login_time = $this->request->time();
		$user->login_ip = $this->request->ip(1);
		$user->save();

		$user['session_key'] = $sessionKey;
		Session::set('user_info', $user);

		$sessionId = session_id();
		$extResult['session_id'] = $sessionId;

		return Hint::result($user, $extResult);
	}

	/**
	 * 获取微信登录结果
	 *
	 * @param string $code
	 * @return array
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
	 * @throws \app\common\exception\WechatException
	 */
	private function getWechatLoginResult($code){
		$result = $this->miniProgram->auth->session($code);
		WechatValidate::validate($result);

		return [$result['session_key'], $result['openid']];
	}

	/**
	 * 获取微信登录结果
	 *
	 * @param string $code
	 * @return array
	 */
	private function getAlipayLoginResult($code){
		//		$request = new AlipaySystemOauthTokenRequest();
		//		$request->setGrantType("authorization_code");
		//		$request->setCode($code);
		//		$result = $this->aliProgram->execute($request);
		//		array(6) {
		//			["access_token"] => string(40) "authbseB7830b6a06cc24d97ac05d017bb295D27"
		//			["alipay_user_id"] => string(32) "20880072601077803922830082716327"
		//			["expires_in"] => int(31536000)
		//			["re_expires_in"] => int(31536000)
		//			["refresh_token"] => string(40) "authbseB4d5cbaac75394f688c04e0d799d69B27"
		//			["user_id"] => string(16) "2088722214313276"
		//}
		//		return [$result['access_token'], $result['user_id']];
		throw new \RuntimeException("not!");
	}

	/**
	 * 制作用户信息
	 *
	 * @param string $openid
	 * @param string $origin
	 * @return \app\common\model\User
	 */
	private function makeUser($openid, $origin){
		$pid = $this->request->param('share_uid/d', 0);
		$user = new User([
			'nickname'        => $this->request->param('nickName', '用户'.date('YmdHis')),
			'gender'          => $this->request->param('gender', 1),
			'openid'          => $openid,
			'avatar'          => $this->request->param('avatarUrl', ''),
			'language'        => $this->request->param('language', 'zh_CN'),
			'country'         => $this->request->param('country', '中国'),
			'province'        => $this->request->param('province', ''), 'city' => $this->request->param('city', ''),
			'energy'          => 0,
			'origin'          => $origin,
			'pid'             => $pid,
			'last_login_time' => time(),
			'last_login_ip'   => $this->request->ip(),
		]);

		if($user->save() === false){
			Hint::outputError("登录失败");
		}

		return $user;
	}
}
